# -*- coding: utf-8 -*-
"""
Windows Process Spy - 命令行版本
提供简单的命令行接口来检测窗口和控件
"""

import sys
import argparse
from modules.app.gui import WindowSpy


def list_windows():
    """列出所有窗口"""
    spy = WindowSpy()
    windows = spy.get_all_windows()
    
    print(f"找到 {len(windows)} 个窗口:")
    print("-" * 80)
    print(f"{'标题':<30} {'类名':<20} {'进程ID':<8} {'进程名':<15}")
    print("-" * 80)
    
    for window in windows:
        print(f"{window.title[:29]:<30} {window.class_name[:19]:<20} "
              f"{window.process_id:<8} {window.process_name[:14]:<15}")


def find_window_by_title(title):
    """根据标题查找窗口"""
    spy = WindowSpy()
    window = spy.get_window_by_title(title)
    
    if window:
        print(f"找到窗口: {window.title}")
        print(f"句柄: {window.hwnd}")
        print(f"类名: {window.class_name}")
        print(f"进程ID: {window.process_id}")
        print(f"进程名: {window.process_name}")
        print(f"位置: {window.rect}")
        print(f"控件数量: {len(window.controls)}")
        
        if window.controls:
            print("\n控件列表:")
            for i, control in enumerate(window.controls, 1):
                print(f"{i}. {control.text or '[无文本]'} ({control.class_name}) - ID: {control.control_id}")
    else:
        print(f"未找到标题包含 '{title}' 的窗口")


def find_window_by_class(class_name):
    """根据类名查找窗口"""
    spy = WindowSpy()
    window = spy.get_window_by_class(class_name)
    
    if window:
        print(f"找到窗口: {window.title}")
        print(f"句柄: {window.hwnd}")
        print(f"类名: {window.class_name}")
        print(f"进程ID: {window.process_id}")
        print(f"进程名: {window.process_name}")
        print(f"位置: {window.rect}")
        print(f"控件数量: {len(window.controls)}")
        
        if window.controls:
            print("\n控件列表:")
            for i, control in enumerate(window.controls, 1):
                print(f"{i}. {control.text or '[无文本]'} ({control.class_name}) - ID: {control.control_id}")
    else:
        print(f"未找到类名包含 '{class_name}' 的窗口")


def find_window_by_process(process_name):
    """根据进程名查找窗口"""
    spy = WindowSpy()
    windows = spy.get_window_by_process(process_name)
    
    if windows:
        print(f"找到 {len(windows)} 个进程 '{process_name}' 的窗口:")
        for i, window in enumerate(windows, 1):
            print(f"\n{i}. {window.title}")
            print(f"   句柄: {window.hwnd}")
            print(f"   类名: {window.class_name}")
            print(f"   进程ID: {window.process_id}")
            print(f"   位置: {window.rect}")
            print(f"   控件数量: {len(window.controls)}")
    else:
        print(f"未找到进程名包含 '{process_name}' 的窗口")


def show_window_details(hwnd):
    """显示指定句柄的窗口详细信息"""
    spy = WindowSpy()
    windows = spy.get_all_windows()
    
    target_window = None
    for window in windows:
        if window.hwnd == hwnd:
            target_window = window
            break
    
    if target_window:
        print(f"窗口详细信息:")
        print(f"标题: {target_window.title}")
        print(f"类名: {target_window.class_name}")
        print(f"句柄: {target_window.hwnd}")
        print(f"进程ID: {target_window.process_id}")
        print(f"进程名: {target_window.process_name}")
        print(f"位置: {target_window.rect}")
        print(f"大小: {target_window.rect[2] - target_window.rect[0]} x {target_window.rect[3] - target_window.rect[1]}")
        print(f"控件数量: {len(target_window.controls)}")
        
        if target_window.controls:
            print("\n控件详细信息:")
            for i, control in enumerate(target_window.controls, 1):
                print(f"{i}. {control.text or '[无文本]'} ({control.class_name})")
                print(f"   句柄: {control.hwnd}")
                print(f"   控件ID: {control.control_id}")
                print(f"   位置: {control.rect}")
                print(f"   父窗口: {control.parent_hwnd}")
                print()
    else:
        print(f"未找到句柄为 {hwnd} 的窗口")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Windows Process Spy - 窗口句柄检测工具')
    parser.add_argument('--list', '-l', action='store_true', help='列出所有窗口')
    parser.add_argument('--title', '-t', help='根据标题查找窗口')
    parser.add_argument('--class', '-c', dest='class_name', help='根据类名查找窗口')
    parser.add_argument('--process', '-p', help='根据进程名查找窗口')
    parser.add_argument('--hwnd', help='显示指定句柄的窗口详细信息')
    
    args = parser.parse_args()
    
    if args.list:
        list_windows()
    elif args.title:
        find_window_by_title(args.title)
    elif args.class_name:
        find_window_by_class(args.class_name)
    elif args.process:
        find_window_by_process(args.process)
    elif args.hwnd:
        try:
            hwnd = int(args.hwnd)
            show_window_details(hwnd)
        except ValueError:
            print("错误: 句柄必须是数字")
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
